# -*- encoding: utf-8 -*-
"""
File Name: inspect_ring_network
Description: 使用Selenium来检查网络告警
Author: 'lirui'
Date: 7/15/2024
Contact: marjey_lee@163.com
Change Activity:
7/15/2024: 重写为Selenium实现
"""

import time
from selenium.webdriver.common.by import By

import ll
from ll.modules.spider.selenium_util import SeleniumUtils

_login_url = 'https://189.8.3.5:31943'
_warning_url = 'https://189.8.3.5:31943/dcnwebsite/dcn/index.html?_language=zh-cn&curMenuId=oamApp.monitoring.alarms.currentAlarm#path=/fmAlarmApp/fmAlarmView&alarmLevel=MAJOR'
_username = 'admin'
_password = 'nk4dGddQ!@#'
_manager_address = '189.8.3.5:31943'


def _login(spider: SeleniumUtils):
    spider.open_browser(_login_url)
    time.sleep(3)
    username_input = spider.find_element(by=By.ID, locator='username')
    username_input.send_keys(_username)
    password_input = spider.find_element(locator='value', by=By.ID, )
    password_input.send_keys(_password)
    login_button = spider.find_element(by=By.ID, locator='submitDataverify')
    login_button.click()
    time.sleep(1)
    return spider


def _preprocess(driver):
    time.sleep(3)  # 等待页面加载
    if driver.check_element_exist('login_warn_confirm'):
        warning_confirm = driver.find_element('login_warn_confirm')
        warning_confirm.click()
    time.sleep(1)
    driver.navigate_to(_warning_url)
    time.sleep(4)  # 等待页面加载
    return driver


def _load_data(driver):
    time.sleep(8)  # 等待数据加载
    alarm_table = driver.find_element('alarmTableLayout_firstChild')
    tbody = driver.find_element_in_element(alarm_table, locator='tbody', by=By.TAG_NAME)
    trs = driver.find_elements_in_element(tbody, locator='tr', by=By.TAG_NAME)
    lines = []
    for tr in trs:
        tds = driver.find_elements_in_element(tr, 'td', By.TAG_NAME)
        line = [td.text for td in tds]
        lines.append(line)
    return lines


def _format_data(data):
    format_data = []
    for d in data:
        if len(d) < 4:
            continue
        latest_occur_time = d[4]
        content = d[2]
        device_source = d[3]
        mapping = {
            'latest_occur_time': latest_occur_time,
            'content': content,
            'device_source': device_source,
            'manager_address': _manager_address
        }
        format_data.append(mapping)
    return format_data


def inspect_xiyuan_campus_controller():
    # 设置Chrome WebDriver的路径（根据你的实际情况修改）
    spider = SeleniumUtils()
    spider = _login(spider)
    spider = _preprocess(spider)
    data = _load_data(spider)
    formatted_data = _format_data(data)
    spider.close_browser()  # 关闭浏览器
    ll.sleep(1)
    return formatted_data


def _main():
    for _ in range(10):
        data = inspect_xiyuan_campus_controller()
        print(data)


if __name__ == '__main__':
    _main()
